/*
 * Copyright 2011 Google Inc.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.google.orkut.orkroid;

import com.google.orkut.client.api.OrkutAdapter;
import com.google.orkut.client.api.OrkutAdapterException;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;

/** Orkroid Authentication Activity. This activity consists of
 *  a screen that lets the user authenticate himself on the
 *  orkut servers. All you have to do is launch this activity 
 *  with <tt>startActivityForResult</tt> and wait for the result,
 *  which will be RESULT_OK if the authentication was successful
 *  or RESULT_CANCELED if the authentication failed. After 
 *  a successful authentication, the Orkroid library's orkut
 *  adapter (static). */
public class OrkroidAuthActivity extends Activity  {
	protected WebView webView;
	protected String verifier = "";
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		webView = new WebView(this);
		setContentView(webView);
		webView.getSettings().setJavaScriptEnabled(true);
		webView.setWebViewClient(new OurWebViewClient());
		webView.loadData("<html><body><br><br><br><div align='center'>" + 
				    "Please wait...</div></body></html>", "text/html", "utf-8");
		(new AuthAsyncTask()).execute();
	}

	protected void endWithSuccess() {
		setResult(RESULT_OK);
		finish();
	}

	protected void endWithFailure(Exception ex) {
		Intent dataIntent = new Intent();
		dataIntent.putExtra("exception", ex);
		setResult(RESULT_CANCELED, dataIntent);
		finish();
	}
	
	private class OurWebViewClient extends WebViewClient {
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			super.onPageStarted(view, url, favicon);
			int i = url.indexOf("oauth_verifier=");
			if (i < 0) return;
			
			i += "oauth_verifier=".length(); // url[i] is now the char right after the '=' sign
			int j = url.indexOf("&", i);
			if (j < 0) verifier = url.substring(i);
			else verifier = url.substring(i,j);
			
			// do URL decoding on the verifier
			verifier = Uri.decode(verifier);
			
			webView.loadData("<html><body><br><br><br><div align='center'>" + 
				    "Authorizing " + verifier + "...</div></body></html>", "text/html", "utf-8");
			
			(new GetPassAsyncTask()).execute();
		}
		
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			// never open a separate activity for browsing content
			return false;
		}
	}
	
	private class AuthAsyncTask extends AsyncTask {
		protected Object doInBackground(Object... arg0) {
			try {
				return Orkroid.getOA().requestAuthURL();
			}
			catch (OrkutAdapterException ex) {
				return ex;
			}
		}
		protected void onPostExecute(Object result) {
			if (result instanceof Exception)
				endWithFailure((Exception)result);
			else
				webView.loadUrl((String)result);
				
		}
	}
	
	private class GetPassAsyncTask extends AsyncTask {
		protected Object doInBackground(Object... arg0) {
			try {
				Orkroid.getOA().authenticate(verifier);
				return null;
			}
			catch (OrkutAdapterException ex) {
				return ex;
			}
		}
		protected void onPostExecute(Object result) {
			Exception ex = (Exception) result;
			if (ex == null) endWithSuccess();
			else endWithFailure(ex);
		}
	}

}
